import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:play_lab/core/helper/string_format_helper.dart';
import 'package:play_lab/data/model/auth/error_model.dart';
import 'package:play_lab/data/model/authorization/authorization_response_model.dart';
import 'package:play_lab/data/model/global/response_model/response_model.dart';
import '../../../../constants/my_strings.dart';
import '../../../../core/route/route.dart';
import '../../../../view/components/show_custom_snackbar.dart';
import '../../../model/auth/verification/email_verification_model.dart';
import '../../../repo/auth/login_repo.dart';

class ForgetPasswordController extends GetxController {
  LoginRepo loginRepo;

  List<String> errors = [];
  String email = '';
  bool isLoading = false;
  bool remember = false;
  bool hasError = false;
  String currentText = "";
  final FocusNode emailFocusNode = FocusNode();
  final FocusNode passwordFocusNode = FocusNode();
  final FocusNode confirmPasswordFocusNode = FocusNode();
  final TextEditingController passwordController = TextEditingController();
  final TextEditingController confirmPasswordController = TextEditingController();

  ForgetPasswordController({required this.loginRepo});

  void initData() {
    checkPasswordStrength = loginRepo.apiClient.getGSData().data?.generalSetting?.securePassword.toString() == '0' ? false : true;
    clearAllData();
    update();
  }

  addError({required String error}) {
    if (!errors.contains(error)) {
      errors.add(error);
      update();
    }
  }

  removeError({required String error}) {
    if (errors.contains(error)) {
      errors.remove(error);
      update();
    }
  }

  void submitForgetPassCode() async {
    if (errors.isNotEmpty) {}
    if (email.isEmpty) {
      addError(error: MyStrings.kEmailNullError);
      return;
    }
    if (email.isNotEmpty) {
      removeError(error: MyStrings.kEmailNullError);
    }

    isLoading = true;
    update();
    String value = email;
    String type = value.contains('@') ? 'email' : 'username';
    String responseEmail = await loginRepo.forgetPassword(type, value);
    if (responseEmail.isNotEmpty) {
      Get.toNamed(RouteHelper.verifyPassCodeScreen, arguments: responseEmail);
    } else {}
    isLoading = false;
    update();
  }

  bool isResendLoading = false;
  void resendForgetPassCode() async {
    isResendLoading = true;
    update();
    String value = email;
    String type = 'email';
    await loginRepo.forgetPassword(type, value);
    isResendLoading = false;
    update();
  }

  void verifyForgetPasswordCode(String value) async {
    if (value.isNotEmpty) {
      isLoading = true;
      update();
      EmailVerificationModel model = await loginRepo.verifyForgetPassCode(value);
      if (model.status == 'success') {
        isLoading = false;
        Get.offAndToNamed(RouteHelper.resetPasswordScreen, arguments: email);
        clearAllData();
      } else {
        isLoading = false;
        update();
        List<String> errorList = [MyStrings.verificationFailed];
        CustomSnackbar.showCustomSnackbar(errorList: model.message?.error ?? errorList, msg: [], isError: true);
      }
    }
  }

  bool checkPasswordStrength = false;

  RegExp regex = RegExp(r'^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[!@#\$&*~]).{8,}$');
  bool isValidPassword(String value) {
    if (value.isEmpty) {
      return false;
    } else {
      if (checkPasswordStrength) {
        if (!regex.hasMatch(value)) {
          return false;
        } else {
          return true;
        }
      } else {
        return true;
      }
    }
  }

  void resetPassword() async {
    if (passwordController.text.isEmpty) {
      CustomSnackbar.showCustomSnackbar(errorList: [MyStrings.passwordNullError], msg: [], isError: true);
      return;
    }
    if (checkPasswordStrength) {
      if (!isValidPassword(passwordController.text.trim())) {
        CustomSnackbar.showCustomSnackbar(errorList: [MyStrings.invalidPassMsg.tr], msg: [], isError: true);
        return;
      }
    }
    if (confirmPasswordController.text.isEmpty) {
      CustomSnackbar.showCustomSnackbar(errorList: [MyStrings.confirmPasswordNullError], msg: [], isError: true);
      return;
    }
    if (passwordController.text.trim() != confirmPasswordController.text.trim()) {
      CustomSnackbar.showCustomSnackbar(errorList: [MyStrings.kMatchPassError], msg: [], isError: true);
      return;
    }

    isLoading = true;
    update();
    try {
      ResponseModel responseModel = await loginRepo.resetPassword(email, passwordController.text.trim());
      isLoading = false;
      update();
      if (responseModel.statusCode == 200) {
        AuthorizationResponseModel model = AuthorizationResponseModel.fromJson(jsonDecode(responseModel.responseJson));
        if (model.status == "success") {
          Get.offAllNamed(RouteHelper.loginScreen);
          CustomSnackbar.showCustomSnackbar(errorList: [], msg: model.message?.success ?? [MyStrings.success], isError: false);
        } else {
          CustomSnackbar.showCustomSnackbar(errorList: model.message?.error ?? [MyStrings.somethingWentWrong], msg: [], isError: true);
        }
      } else {
        CustomSnackbar.showCustomSnackbar(errorList: [responseModel.message], msg: [], isError: true);
      }
    } catch (e) {
      printX("Error in Reset Password");
      CustomSnackbar.showCustomSnackbar(errorList: [MyStrings.somethingWentWrong], msg: [], isError: true);
    }
    isLoading = false;
    update();
  }

  bool hasPasswordFocus = false;
  void changePasswordFocus(bool hasFocus) {
    hasPasswordFocus = hasFocus;
    update();
  }

  List<ErrorModel> passwordValidationRules = [
    ErrorModel(text: MyStrings.hasUpperLetter.tr, hasError: true),
    ErrorModel(text: MyStrings.hasLowerLetter.tr, hasError: true),
    ErrorModel(text: MyStrings.hasDigit.tr, hasError: true),
    ErrorModel(text: MyStrings.hasSpecialChar.tr, hasError: true),
    ErrorModel(text: MyStrings.minSixChar.tr, hasError: true),
  ];

  String? validatePassword(String value) {
    if (value.isEmpty) {
      return MyStrings.enterYourPassword.tr;
    } else {
      if (checkPasswordStrength) {
        if (!regex.hasMatch(value)) {
          return MyStrings.invalidPassMsg.tr;
        } else {
          return null;
        }
      } else {
        return null;
      }
    }
  }

  void updateValidationList(String value) {
    passwordValidationRules[0].hasError = value.contains(RegExp(r'[A-Z]')) ? false : true;
    passwordValidationRules[1].hasError = value.contains(RegExp(r'[a-z]')) ? false : true;
    passwordValidationRules[2].hasError = value.contains(RegExp(r'[0-9]')) ? false : true;
    passwordValidationRules[3].hasError = value.contains(RegExp(r'[!@#$%^&*(),.?":{}|<>]')) ? false : true;
    passwordValidationRules[4].hasError = value.length >= 6 ? false : true;

    update();
  }

  clearAllData() {
    isLoading = false;
    currentText = '';
    passwordController.text = "";
    confirmPasswordController.text = "";
  }
}
